<?php
$dbname = 'ncdb';
$dbhost = 'cougar.wou.edu';
$dbuser = 'ncdb';
$dbpass = 'bdcn';
$db = mysql_connect($dbhost,$dbuser,$dbpass);

function getResourcesForDlg($field,$searchCol) {
	session_start();
	global $stringJSON, $dbname, $db, $db_selected;
	$userid = $_SESSION[UID];
	require_once("../classes/JSON.php");
	
	$searchCol = trim($searchCol);
	if ($searchCol == 'Category') {
		$sql = "SELECT COUNT(LRC.CID) AS CountCol, LTRIM(MC.CatTitle) AS SearchCol
				FROM ncdb_LinkResourceCats AS LRC
				LEFT JOIN ncdb_MainCat AS MC ON MC.CatID = LRC.CID
				GROUP BY LRC.CID
				ORDER BY SearchCol";
	} elseif ($searchCol == 'Subject') {
		$sql = "SELECT COUNT(LRS.SID) AS CountCol, LTRIM(MC.CatTitle) AS SearchCol
				FROM ncdb_LinkResourceSubject AS LRS
				LEFT JOIN ncdb_MainCat AS MC ON MC.CatID = LRS.SID
				GROUP BY LRS.SID
				ORDER BY SearchCol";
	} elseif ($searchCol == 'Sets') {
		$sql = "SELECT COUNT(SSLN.SIID) AS CountCol,SS.Title AS SearchCol,SS.SID AS SSID,SS.SetDesc,SS.DateCreate,SS.Public
			FROM ncdb_SavedSets SS
			LEFT JOIN ncdb_SavedSetLink SSLN ON SSLN.SID = SS.SID
			WHERE
				(SS.Public = 1 OR
				(SS.Public = 0 AND Userid = '$userid')) AND
				SS.Temp <> 1 AND SS.ReportOnly <> 1 AND Type = 'Resource'			
			GROUP BY SS.SID			
			ORDER BY SS.Title
			";
	} else {	
		$sql = "SELECT COUNT($searchCol) AS CountCol,$searchCol AS SearchCol 
				FROM ncdb_Resources 
				GROUP BY SearchCol
				ORDER BY SearchCol
				";
	}	
	$result = mysql_db_query($dbname,$sql);
	if (mysql_num_rows($result)>0) {
		$stringJSON = '({"Resources":[';
		$i=0;
		while ($value = mysql_fetch_assoc($result)) {
			if (!empty($value['SearchCol'])) {
				$newArray = array(
								'ID'        => $i,
								'Count'     => $value['CountCol'],							
								'SearchCol' => $value['SearchCol']
								);
				
				$json = new Services_JSON();
				$stringJSON .= $json->encode($newArray).',';
				$i++;
			}	
		}	
		// Strip last ,
		$strLen = strlen($stringeJSON);
		$stringJSON = substr($stringJSON,0,($strLen-1));
		$stringJSON .= ']})';
	}	
	return $stringJSON;
}

if ($_GET[getResources]==1) {
	$field      = $_GET[field];
	$searchCol = $_GET[searchCol];
	$stringJSON = getResourcesForDlg($field,$searchCol);
	echo $stringJSON;
} elseif ($_GET[getBibRecords]==1) {
	$field      = $_GET[field];
	$defaultCol = $_GET[defaultCol];
	$stringJSON = getBibRecordsForDlg($field,$defaultCol);
	echo $stringJSON;
} 
?>